import sys
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QPushButton, QLabel, QLineEdit, QTextEdit, QComboBox, QCheckBox,
    QRadioButton, QSlider, QProgressBar, QMessageBox, QFileDialog,
    QListWidget, QTabWidget, QStatusBar, QMenuBar, QMenu,
    QGroupBox, QDateEdit, QTimeEdit, QSpinBox, QDoubleSpinBox,
    QGridLayout, QDialog, QDialogButtonBox
)
from PyQt6.QtGui import QIcon, QPixmap, QFont, QAction
from PyQt6.QtCore import Qt, QSize, QDate, QTime, QTimer, QThread

class PyQt6Guide(QMainWindow):
    def __init__(self):
        super().__init__()
        
        # 设置主窗口属性
        self.setWindowTitle("PyQt6 使用指南")
        self.setGeometry(100, 100, 900, 700)
        self.setWindowIcon(QIcon("icon.png"))  # 替换为你的图标路径
        
        # 创建菜单栏
        self.create_menu()
        
        # 创建状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_bar.showMessage("就绪")
        
        # 创建主部件和布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        
        # 创建标签页
        self.tabs = QTabWidget()
        main_layout.addWidget(self.tabs)
        
        # 添加各个标签页
        self.tabs.addTab(self.create_widgets_tab(), "基本组件")
        self.tabs.addTab(self.create_layouts_tab(), "布局管理")
        self.tabs.addTab(self.create_signals_tab(), "信号与槽")
        self.tabs.addTab(self.create_dialogs_tab(), "对话框")
        self.tabs.addTab(self.create_advanced_tab(), "高级功能")
        
        # 添加退出按钮
        exit_button = QPushButton("退出程序")
        exit_button.clicked.connect(self.close)
        exit_button.setStyleSheet("background-color: #ff6b6b; color: white; font-weight: bold;")
        main_layout.addWidget(exit_button)
        
        # 创建定时器更新状态栏时间
        self.status_timer = QTimer()
        self.status_timer.timeout.connect(self.update_statusbar)
        self.status_timer.start(1000)  # 每秒更新一次
        
        # 创建计时器定时器
        self.count_timer = QTimer()
        self.count_timer.timeout.connect(self.update_timer)

    def create_menu(self):
        menubar = self.menuBar()
        
        # 文件菜单
        file_menu = menubar.addMenu("文件")
        
        new_action = QAction("新建", self)
        new_action.setShortcut("Ctrl+N")
        file_menu.addAction(new_action)
        
        open_action = QAction("打开", self)
        open_action.setShortcut("Ctrl+O")
        open_action.triggered.connect(self.open_file)
        file_menu.addAction(open_action)
        
        save_action = QAction("保存", self)
        save_action.setShortcut("Ctrl+S")
        file_menu.addAction(save_action)
        
        file_menu.addSeparator()
        
        exit_action = QAction("退出", self)
        exit_action.setShortcut("Ctrl+Q")
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
        # 编辑菜单
        edit_menu = menubar.addMenu("编辑")
        edit_menu.addAction("复制")
        edit_menu.addAction("粘贴")
        edit_menu.addAction("剪切")
        
        # 帮助菜单
        help_menu = menubar.addMenu("帮助")
        about_action = QAction("关于", self)
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)

    def update_statusbar(self):
        current_time = QTime.currentTime().toString("hh:mm:ss")
        self.status_bar.showMessage(f"就绪 | 当前时间: {current_time}")

    def create_widgets_tab(self):
        """创建基本组件标签页"""
        tab = QWidget()
        layout = QVBoxLayout(tab)
        
        # 标题
        title = QLabel("PyQt6 基本组件示例")
        title.setFont(QFont("Arial", 16, QFont.Weight.Bold))
        title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(title)
        
        # 使用网格布局组织组件
        grid_layout = QHBoxLayout()
        left_column = QVBoxLayout()
        right_column = QVBoxLayout()
        
        # 左侧列
        # 1. 按钮
        button_group = QGroupBox("按钮")
        button_layout = QVBoxLayout(button_group)
        
        btn1 = QPushButton("普通按钮")
        btn2 = QPushButton("带图标的按钮", self)
        btn2.setIcon(QIcon("button_icon.png"))  # 替换为实际图标路径
        btn2.setIconSize(QSize(16, 16))
        
        btn3 = QPushButton("禁用按钮")
        btn3.setEnabled(False)
        
        button_layout.addWidget(btn1)
        button_layout.addWidget(btn2)
        button_layout.addWidget(btn3)
        left_column.addWidget(button_group)
        
        # 2. 文本输入
        text_group = QGroupBox("文本输入")
        text_layout = QVBoxLayout(text_group)
        
        line_edit = QLineEdit()
        line_edit.setPlaceholderText("单行文本框...")
        
        text_edit = QTextEdit()
        text_edit.setPlaceholderText("多行文本框...")
        
        text_layout.addWidget(QLabel("单行文本:"))
        text_layout.addWidget(line_edit)
        text_layout.addWidget(QLabel("多行文本:"))
        text_layout.addWidget(text_edit)
        left_column.addWidget(text_group)
        
        # 3. 选择控件
        select_group = QGroupBox("选择控件")
        select_layout = QVBoxLayout(select_group)
        
        combo = QComboBox()
        combo.addItems(["选项1", "选项2", "选项3", "选项4"])
        
        list_widget = QListWidget()
        list_widget.addItems(["列表项1", "列表项2", "列表项3", "列表项4"])
        
        select_layout.addWidget(QLabel("下拉框:"))
        select_layout.addWidget(combo)
        select_layout.addWidget(QLabel("列表框:"))
        select_layout.addWidget(list_widget)
        left_column.addWidget(select_group)
        
        # 右侧列
        # 1. 复选框和单选按钮
        check_radio_group = QGroupBox("复选框和单选按钮")
        check_radio_layout = QVBoxLayout(check_radio_group)
        
        checkbox1 = QCheckBox("复选框 1")
        checkbox2 = QCheckBox("复选框 2 (已选中)")
        checkbox2.setChecked(True)
        
        radio1 = QRadioButton("单选按钮 1")
        radio2 = QRadioButton("单选按钮 2 (已选中)")
        radio2.setChecked(True)
        
        check_radio_layout.addWidget(checkbox1)
        check_radio_layout.addWidget(checkbox2)
        check_radio_layout.addWidget(radio1)
        check_radio_layout.addWidget(radio2)
        right_column.addWidget(check_radio_group)
        
        # 2. 滑块和进度条
        slider_group = QGroupBox("滑块和进度条")
        slider_layout = QVBoxLayout(slider_group)
        
        slider = QSlider(Qt.Orientation.Horizontal)
        slider.setRange(0, 100)
        slider.setValue(50)
        
        progress = QProgressBar()
        progress.setRange(0, 100)
        progress.setValue(75)
        
        slider_layout.addWidget(QLabel("滑块:"))
        slider_layout.addWidget(slider)
        slider_layout.addWidget(QLabel("进度条:"))
        slider_layout.addWidget(progress)
        right_column.addWidget(slider_group)
        
        # 3. 日期和时间
        datetime_group = QGroupBox("日期和时间")
        datetime_layout = QVBoxLayout(datetime_group)
        
        date_edit = QDateEdit()
        date_edit.setDate(QDate.currentDate())
        
        time_edit = QTimeEdit()
        time_edit.setTime(QTime.currentTime())
        
        spinbox = QSpinBox()
        spinbox.setRange(0, 100)
        spinbox.setValue(42)
        
        double_spinbox = QDoubleSpinBox()
        double_spinbox.setRange(0, 10)
        double_spinbox.setValue(3.14)
        double_spinbox.setSingleStep(0.1)
        
        datetime_layout.addWidget(QLabel("日期选择:"))
        datetime_layout.addWidget(date_edit)
        datetime_layout.addWidget(QLabel("时间选择:"))
        datetime_layout.addWidget(time_edit)
        datetime_layout.addWidget(QLabel("整数输入:"))
        datetime_layout.addWidget(spinbox)
        datetime_layout.addWidget(QLabel("浮点数输入:"))
        datetime_layout.addWidget(double_spinbox)
        right_column.addWidget(datetime_group)
        
        # 添加左右列到网格布局
        grid_layout.addLayout(left_column)
        grid_layout.addLayout(right_column)
        layout.addLayout(grid_layout)
        
        return tab

    def create_layouts_tab(self):
        """创建布局管理标签页"""
        tab = QWidget()
        layout = QVBoxLayout(tab)
        
        title = QLabel("PyQt6 布局管理")
        title.setFont(QFont("Arial", 16, QFont.Weight.Bold))
        title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(title)
        
        # 水平布局示例
        hbox_group = QGroupBox("水平布局 (QHBoxLayout)")
        hbox_layout = QHBoxLayout(hbox_group)
        
        for i in range(1, 6):
            btn = QPushButton(f"按钮 {i}")
            hbox_layout.addWidget(btn)
        
        layout.addWidget(hbox_group)
        
        # 垂直布局示例
        vbox_group = QGroupBox("垂直布局 (QVBoxLayout)")
        vbox_layout = QVBoxLayout(vbox_group)
        
        for i in range(1, 6):
            btn = QPushButton(f"按钮 {i}")
            vbox_layout.addWidget(btn)
        
        layout.addWidget(vbox_group)
        
        # 网格布局示例
        grid_group = QGroupBox("网格布局 (QGridLayout)")
        grid_widget = QWidget()
        grid_layout = QGridLayout(grid_widget)
        
        positions = [(i, j) for i in range(3) for j in range(3)]
        for position in positions:
            row, col = position
            btn = QPushButton(f"{row},{col}")
            grid_layout.addWidget(btn, row, col)
        
        grid_group.setLayout(QVBoxLayout())
        grid_group.layout().addWidget(grid_widget)
        layout.addWidget(grid_group)
        
        # 嵌套布局示例
        nested_group = QGroupBox("嵌套布局示例")
        main_nested_layout = QHBoxLayout(nested_group)
        
        left_side = QVBoxLayout()
        left_side.addWidget(QLabel("左侧区域"))
        left_side.addWidget(QPushButton("按钮1"))
        left_side.addWidget(QPushButton("按钮2"))
        
        right_side = QGridLayout()
        right_side.addWidget(QLabel("右上"), 0, 0)
        right_side.addWidget(QPushButton("按钮3"), 0, 1)
        right_side.addWidget(QLabel("右下"), 1, 0, 1, 2)
        
        main_nested_layout.addLayout(left_side)
        main_nested_layout.addLayout(right_side)
        layout.addWidget(nested_group)
        
        return tab

    def create_signals_tab(self):
        """创建信号与槽标签页"""
        tab = QWidget()
        layout = QVBoxLayout(tab)
        
        title = QLabel("信号与槽机制")
        title.setFont(QFont("Arial", 16, QFont.Weight.Bold))
        title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(title)
        
        # 按钮点击示例
        btn_click_group = QGroupBox("按钮点击事件")
        btn_click_layout = QVBoxLayout(btn_click_group)
        
        self.click_label = QLabel("点击按钮测试信号连接")
        self.click_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        click_btn = QPushButton("点击我!")
        click_btn.clicked.connect(self.on_button_click)
        
        btn_click_layout.addWidget(self.click_label)
        btn_click_layout.addWidget(click_btn)
        layout.addWidget(btn_click_group)
        
        # 文本改变示例
        text_change_group = QGroupBox("文本改变事件")
        text_change_layout = QVBoxLayout(text_change_group)
        
        self.text_input = QLineEdit()
        self.text_input.setPlaceholderText("在此输入文本...")
        self.text_input.textChanged.connect(self.on_text_changed)
        
        self.text_output = QLabel("输入内容将显示在这里")
        self.text_output.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        text_change_layout.addWidget(self.text_input)
        text_change_layout.addWidget(self.text_output)
        layout.addWidget(text_change_group)
        
        # 下拉框选择示例
        combo_group = QGroupBox("下拉框选择事件")
        combo_layout = QVBoxLayout(combo_group)
        
        self.combo_box = QComboBox()
        self.combo_box.addItems(["红色", "绿色", "蓝色", "黄色", "紫色"])
        self.combo_box.currentIndexChanged.connect(self.on_combo_changed)
        
        self.color_display = QLabel("颜色预览")
        self.color_display.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.color_display.setStyleSheet("background-color: #ff0000; color: white;")
        self.color_display.setMinimumHeight(60)
        
        combo_layout.addWidget(self.combo_box)
        combo_layout.addWidget(self.color_display)
        layout.addWidget(combo_group)
        
        return tab

    def create_dialogs_tab(self):
        """创建对话框标签页"""
        tab = QWidget()
        layout = QVBoxLayout(tab)
        
        title = QLabel("对话框使用示例")
        title.setFont(QFont("Arial", 16, QFont.Weight.Bold))
        title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(title)
        
        # 信息对话框
        info_group = QGroupBox("信息对话框")
        info_layout = QVBoxLayout(info_group)
        
        info_btn = QPushButton("显示信息对话框")
        info_btn.clicked.connect(self.show_info_dialog)
        info_layout.addWidget(info_btn)
        layout.addWidget(info_group)
        
        # 警告对话框
        warning_group = QGroupBox("警告对话框")
        warning_layout = QVBoxLayout(warning_group)
        
        warning_btn = QPushButton("显示警告对话框")
        warning_btn.clicked.connect(self.show_warning_dialog)
        warning_layout.addWidget(warning_btn)
        layout.addWidget(warning_group)
        
        # 问题对话框
        question_group = QGroupBox("问题对话框")
        question_layout = QVBoxLayout(question_group)
        
        question_btn = QPushButton("显示问题对话框")
        question_btn.clicked.connect(self.show_question_dialog)
        question_layout.addWidget(question_btn)
        layout.addWidget(question_group)
        
        # 文件对话框
        file_group = QGroupBox("文件对话框")
        file_layout = QVBoxLayout(file_group)
        
        open_btn = QPushButton("打开文件")
        open_btn.clicked.connect(self.open_file_dialog)
        
        save_btn = QPushButton("保存文件")
        save_btn.clicked.connect(self.save_file_dialog)
        
        file_layout.addWidget(open_btn)
        file_layout.addWidget(save_btn)
        layout.addWidget(file_group)
        
        # 自定义对话框
        custom_group = QGroupBox("自定义对话框")
        custom_layout = QVBoxLayout(custom_group)
        
        custom_btn = QPushButton("显示自定义对话框")
        custom_btn.clicked.connect(self.show_custom_dialog)
        custom_layout.addWidget(custom_btn)
        layout.addWidget(custom_group)
        
        return tab

    def create_advanced_tab(self):
        """创建高级功能标签页"""
        tab = QWidget()
        layout = QVBoxLayout(tab)
        
        title = QLabel("高级功能")
        title.setFont(QFont("Arial", 16, QFont.Weight.Bold))
        title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(title)
        
        # 样式表示例
        style_group = QGroupBox("样式表 (CSS样式)")
        style_layout = QVBoxLayout(style_group)
        
        styled_btn = QPushButton("样式化按钮")
        styled_btn.setStyleSheet("""
            QPushButton {
                background-color: #3498db;
                color: white;
                border-radius: 10px;
                padding: 10px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
            QPushButton:pressed {
                background-color: #1c6ea4;
            }
        """)
        
        styled_label = QLabel("样式化标签")
        styled_label.setStyleSheet("""
            QLabel {
                background-color: #2ecc71;
                color: white;
                padding: 10px;
                border: 2px solid #27ae60;
                border-radius: 5px;
                font-style: italic;
            }
        """)
        
        style_layout.addWidget(styled_btn)
        style_layout.addWidget(styled_label)
        layout.addWidget(style_group)
        
        # 定时器示例
        timer_group = QGroupBox("定时器")
        timer_layout = QVBoxLayout(timer_group)
        
        self.timer_label = QLabel("00:00")
        self.timer_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.timer_label.setFont(QFont("Arial", 24, QFont.Weight.Bold))
        
        self.timer_value = 0
        self.timer_running = False
        
        timer_btn = QPushButton("开始/停止定时器")
        timer_btn.clicked.connect(self.toggle_timer)
        
        reset_btn = QPushButton("重置定时器")
        reset_btn.clicked.connect(self.reset_timer)
        
        timer_layout.addWidget(self.timer_label)
        timer_layout.addWidget(timer_btn)
        timer_layout.addWidget(reset_btn)
        layout.addWidget(timer_group)
        
        # 多线程示例
        thread_group = QGroupBox("多线程")
        thread_layout = QVBoxLayout(thread_group)
        
        thread_info = QLabel("在实际应用中，长时间任务应在单独线程中运行\n以避免阻塞UI线程")
        thread_info.setWordWrap(True)
        
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        
        thread_btn = QPushButton("模拟耗时任务")
        thread_btn.clicked.connect(self.simulate_long_task)
        
        thread_layout.addWidget(thread_info)
        thread_layout.addWidget(self.progress_bar)
        thread_layout.addWidget(thread_btn)
        layout.addWidget(thread_group)
        
        return tab

    # ======================
    # 事件处理函数
    # ======================
    def on_button_click(self):
        self.click_label.setText("按钮被点击了!")
        self.click_label.setStyleSheet("color: green; font-weight: bold;")
        QTimer.singleShot(2000, lambda: self.click_label.setText("点击按钮测试信号连接"))
        QTimer.singleShot(2000, lambda: self.click_label.setStyleSheet(""))
    
    def on_text_changed(self, text):
        self.text_output.setText(f"你输入了: {text}")
    
    def on_combo_changed(self, index):
        colors = {
            0: ("红色", "#ff0000"),
            1: ("绿色", "#00ff00"),
            2: ("蓝色", "#0000ff"),
            3: ("黄色", "#ffff00"),
            4: ("紫色", "#800080")
        }
        name, code = colors.get(index, ("红色", "#ff0000"))
        self.color_display.setText(name)
        self.color_display.setStyleSheet(f"background-color: {code}; color: white;")
    
    def show_info_dialog(self):
        QMessageBox.information(self, "信息", "这是一个信息对话框示例")
    
    def show_warning_dialog(self):
        QMessageBox.warning(self, "警告", "这是一个警告对话框示例")
    
    def show_question_dialog(self):
        reply = QMessageBox.question(
            self, "问题", "你确定要继续吗?",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
        )
        if reply == QMessageBox.StandardButton.Yes:
            self.status_bar.showMessage("用户选择了: 是", 3000)
        else:
            self.status_bar.showMessage("用户选择了: 否", 3000)
    
    def open_file_dialog(self):
        file_name, _ = QFileDialog.getOpenFileName(
            self, "打开文件", "", "所有文件 (*);;文本文件 (*.txt);;图片 (*.png *.jpg)"
        )
        if file_name:
            self.status_bar.showMessage(f"已选择文件: {file_name}", 5000)
    
    def save_file_dialog(self):
        file_name, _ = QFileDialog.getSaveFileName(
            self, "保存文件", "", "所有文件 (*);;文本文件 (*.txt);;图片 (*.png *.jpg)"
        )
        if file_name:
            self.status_bar.showMessage(f"文件将保存到: {file_name}", 5000)
    
    def show_custom_dialog(self):
        dialog = QDialog(self)
        dialog.setWindowTitle("自定义对话框")
        dialog.setFixedSize(300, 200)
        
        layout = QVBoxLayout(dialog)
        
        label = QLabel("这是一个自定义对话框示例")
        label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(label)
        
        btn_box = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
        )
        btn_box.accepted.connect(dialog.accept)
        btn_box.rejected.connect(dialog.reject)
        layout.addWidget(btn_box)
        
        if dialog.exec() == QDialog.DialogCode.Accepted:
            self.status_bar.showMessage("自定义对话框: 用户选择了确定", 3000)
        else:
            self.status_bar.showMessage("自定义对话框: 用户选择了取消", 3000)
    
    def toggle_timer(self):
        self.timer_running = not self.timer_running
        if self.timer_running:
            self.count_timer.start(100)  # 每100毫秒更新一次
        else:
            self.count_timer.stop()
    
    def reset_timer(self):
        self.timer_value = 0
        self.update_timer_display()
    
    def update_timer(self):
        self.timer_value += 1
        self.update_timer_display()
    
    def update_timer_display(self):
        seconds = self.timer_value / 10
        self.timer_label.setText(f"{seconds:.1f} 秒")
    
    def simulate_long_task(self):
        self.progress_bar.setValue(0)
        self.status_bar.showMessage("模拟耗时任务开始...")
        
        # 在实际应用中，这里应该使用QThread
        for i in range(1, 101):
            self.progress_bar.setValue(i)
            QApplication.processEvents()  # 允许UI更新
            QThread.msleep(30)  # 模拟工作延迟
        
        self.status_bar.showMessage("耗时任务完成!", 3000)
    
    def open_file(self):
        self.status_bar.showMessage("打开文件菜单被点击", 2000)
    
    def show_about(self):
        QMessageBox.about(self, "关于 PyQt6 指南", 
            "这是一个 PyQt6 使用指南示例程序\n\n"
            "展示了 PyQt6 的基本组件、布局、信号槽机制以及常用功能。\n\n"
            "版本: 1.0\n"
            "作者: Aiden")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    # 设置应用样式
    app.setStyle("Fusion")
    
    # 设置全局字体
    font = QFont("Arial", 10)
    app.setFont(font)
    
    window = PyQt6Guide()
    window.show()
    sys.exit(app.exec())